package com.doubi.controller.generator;

import com.doubi.model.sys.GenTable;
import com.doubi.service.GenTableService;
import com.doubi.vo.AppModel;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 代码生成 操作处理
 *
 * @author MrDoubi
 */
@Controller
@RequestMapping("/toolGen")
public class GenController {

    @Autowired
    private GenTableService genTableService;


    @RequiresPermissions("toolGen:view")
    @GetMapping("view")
    public String view() {
        return "web/toolGen/view";
    }

    @GetMapping("write")
    public String write(String tableName, Model model) {
        model.addAttribute("tableName", tableName);
        return "web/toolGen/write";
    }

    /**
     * 查询代码生成列表
     */
    @RequiresPermissions("toolGen:list")
    @PostMapping("/list")
    @ResponseBody
    public AppModel genList() {
        List<GenTable> list = genTableService.selectDbTableList();
        return AppModel.success(list);
    }

    /**
     * 生成代码
     */
    @RequiresPermissions("toolGen:code")
    @GetMapping("/genCode/{tableName}")
    public void genCode(HttpServletResponse response,
                        @PathVariable("tableName") String tableName, String moduleName
    ) throws IOException {
        byte[] data = genTableService.generatorCode(tableName, moduleName);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\""+tableName+"_doubi.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}